<template>
  <div class="learning-container">
    <el-row :gutter="20">
      <!-- 左侧课程大纲 -->
      <el-col :span="6">
        <el-card class="course-outline-card">
          <template #header>
            <div class="card-header">
              <h3>{{ course.title }}</h3>
              <el-progress
                :percentage="enrollment?.progressPercentage || 0"
                :show-text="false"
              />
            </div>
          </template>
          
          <div class="modules-tree">
            <div
              v-for="module in modules"
              :key="module.id"
              class="module-item"
            >
              <div class="module-header">
                <h4>{{ module.title }}</h4>
              </div>
              
              <div class="lessons-list">
                <div
                  v-for="lesson in getLessonsByModule(module.id)"
                  :key="lesson.id"
                  class="lesson-item"
                  :class="{ active: currentLesson?.id === lesson.id, completed: isLessonCompleted(lesson.id) }"
                  @click="selectLesson(lesson)"
                >
                  <div class="lesson-info">
                    <el-icon v-if="isLessonCompleted(lesson.id)" class="completed-icon">
                      <Check />
                    </el-icon>
                    <el-icon v-else class="lesson-type-icon">
                      <Video v-if="lesson.lessonType === 'VIDEO'" />
                      <Document v-if="lesson.lessonType === 'DOCUMENT'" />
                      <Reading v-if="lesson.lessonType === 'TEXT'" />
                    </el-icon>
                    <span class="lesson-title">{{ lesson.title }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 中间学习区域 -->
      <el-col :span="12">
        <el-card class="learning-content-card">
          <template #header>
            <div class="card-header">
              <div class="lesson-info">
                <h3>{{ currentLesson?.title || '请选择课时开始学习' }}</h3>
                <el-tag
                  v-if="currentLesson"
                  :type="getLessonTypeTagType(currentLesson.lessonType)"
                  size="small"
                >
                  {{ getLessonTypeText(currentLesson.lessonType) }}
                </el-tag>
              </div>
              <div class="lesson-actions">
                <el-button
                  v-if="currentLesson"
                  type="primary"
                  @click="completeLesson"
                  :disabled="isLessonCompleted(currentLesson.id)"
                >
                  完成学习
                </el-button>
              </div>
            </div>
          </template>
          
          <div v-if="currentLesson" class="lesson-content">
            <!-- 视频课时 -->
            <div v-if="currentLesson.lessonType === 'VIDEO'" class="video-content">
              <div class="video-player">
                <video
                  ref="videoPlayer"
                  :src="currentLesson.videoUrl"
                  controls
                  @timeupdate="onVideoTimeUpdate"
                  @play="onVideoPlay"
                  @pause="onVideoPause"
                  @ended="onVideoEnded"
                >
                  您的浏览器不支持视频播放。
                </video>
              </div>
              <div class="video-controls">
                <span>已观看: {{ formatTime(viewedDuration) }} / {{ formatTime(currentLesson.estimatedDuration * 60) }}</span>
                <el-progress
                  :percentage="getVideoProgress()"
                  :show-text="false"
                />
              </div>
            </div>
            
            <!-- 文档课时 -->
            <div v-else-if="currentLesson.lessonType === 'DOCUMENT'" class="document-content">
              <iframe
                v-if="currentLesson.documentUrl"
                :src="currentLesson.documentUrl"
                class="document-viewer"
                frameborder="0"
              ></iframe>
              <div v-else class="no-document">
                <el-icon><Document /></el-icon>
                <p>暂无文档内容</p>
              </div>
            </div>
            
            <!-- 图文课时 -->
            <div v-else-if="currentLesson.lessonType === 'TEXT'" class="text-content">
              <div class="text-viewer" v-html="currentLesson.content"></div>
            </div>
            
            <!-- 其他类型 -->
            <div v-else class="other-content">
              <p>该课时类型暂不支持在线学习</p>
            </div>
          </div>
          
          <div v-else class="no-lesson-selected">
            <el-icon><Reading /></el-icon>
            <p>请从左侧课程大纲中选择一个课时开始学习</p>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧讨论区 -->
      <el-col :span="6">
        <el-card class="discussion-card">
          <template #header>
            <div class="card-header">
              <h3>讨论区</h3>
              <div class="discussion-actions">
                <el-button
                  v-if="currentLesson"
                  type="primary"
                  size="small"
                  @click="askQuestion"
                >
                  提问
                </el-button>
                <el-button
                  size="small"
                  @click="refreshQuestions"
                >
                  刷新
                </el-button>
                <el-button
                  size="small"
                  @click="viewAllCourseQuestions"
                >
                  全部问题
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="questions-list">
            <div
              v-for="question in lessonQuestions"
              :key="question.id"
              class="question-item"
              @click="viewQuestion(question.id)"
            >
              <p class="question-title">{{ question.title }}</p>
              <div class="question-meta">
                <span>{{ question.userName }}</span>
                <span>{{ formatDate(question.createTime) }}</span>
              </div>
            </div>
            
            <p v-if="lessonQuestions.length === 0" class="no-questions">
              暂无相关问题
            </p>
          </div>
        </el-card>
        
        <!-- 学习进度统计 -->
        <el-card class="progress-stats-card">
          <template #header>
            <h3>学习统计</h3>
          </template>
          
          <div class="stats-info">
            <div class="stat-item">
              <p class="stat-label">总课时</p>
              <p class="stat-value">{{ enrollment?.totalLessons || 0 }}</p>
            </div>
            <div class="stat-item">
              <p class="stat-label">已完成</p>
              <p class="stat-value">{{ enrollment?.completedLessons || 0 }}</p>
            </div>
            <div class="stat-item">
              <p class="stat-label">进度</p>
              <p class="stat-value">{{ enrollment?.progressPercentage || 0 }}%</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Check,
  Video,
  Document,
  Reading
} from '@element-plus/icons-vue'
import request from '../../utils/request'

// 路由
const route = useRoute()
const router = useRouter()

// 视频播放器引用
const videoPlayer = ref<HTMLVideoElement | null>(null)

// 数据
const course = ref({
  id: 0,
  title: ''
})

const modules = ref([])
const lessons = ref([])
const enrollment = ref(null)
const currentLesson = ref(null)
const lessonProgress = ref([])
const lessonQuestions = ref([])
const viewedDuration = ref(0)
const videoPlayInterval = ref<number | null>(null)

// 获取课程模块
const fetchLearningInfo = async () => {
  try {
    const courseId = route.params.id
    
    // 获取课程信息
    const courseResponse = await request.get(`/api/study/courses/${courseId}`)
    course.value = courseResponse.data
    
    // 获取课程模块
    const modulesResponse = await request.get(`/api/study/courses/${courseId}/modules`)
    modules.value = modulesResponse.data
    
    // 如果没有模块，给出提示
    if (!modules.value || modules.value.length === 0) {
      ElMessage.warning('该课程暂无模块信息')
    }
    
    // 获取所有课时
    for (const module of modules.value) {
      const lessonsResponse = await request.get(`/api/study/courses/modules/${module.id}/lessons`)
      lessons.value = [...lessons.value, ...lessonsResponse.data]
    }
    
    // 获取用户报名信息
    const enrollmentResponse = await request.get(`/api/study/enrollments/courses/${courseId}/status`)
    enrollment.value = enrollmentResponse.data
    
    // 获取学习进度
    const progressResponse = await request.get(`/api/study/progress/courses/${courseId}`)
    lessonProgress.value = progressResponse.data
    
    // 默认选择第一个课时
    if (lessons.value.length > 0) {
      selectLesson(lessons.value[0])
    }
  } catch (error: any) {
    console.error('获取学习信息失败:', error)
    if (error.response && error.response.status === 403) {
      ElMessage.error('权限不足，请先登录')
    } else {
      ElMessage.error('获取学习信息失败')
    }
  }
}

// 根据模块ID获取课时
const getLessonsByModule = (moduleId: number) => {
  return lessons.value.filter((lesson: any) => lesson.moduleId === moduleId)
}

// 选择课时
const selectLesson = async (lesson: any) => {
  currentLesson.value = lesson
  
  // 记录开始学习
  try {
    await request.post(`/api/study/progress/lessons/${lesson.id}/start`)
  } catch (error) {
    // 忽略错误
  }
  
  // 获取课时相关问题
  fetchLessonQuestions(lesson.id)
}

// 完成课时学习
const completeLesson = async () => {
  if (!currentLesson.value) return
  
  try {
    await request.post(`/api/study/progress/lessons/${currentLesson.value.id}/complete`)
    ElMessage.success('课时学习完成')
    
    // 更新学习进度
    fetchLearningInfo()
  } catch (error) {
    ElMessage.error('完成课时学习失败')
  }
}

// 检查课时是否已完成
const isLessonCompleted = (lessonId: number) => {
  return lessonProgress.value.some(
    (progress: any) => progress.lessonId === lessonId && progress.status === 'COMPLETED'
  )
}

// 视频时间更新
const onVideoTimeUpdate = () => {
  if (videoPlayer.value) {
    viewedDuration.value = videoPlayer.value.currentTime
    
    // 每30秒更新一次进度
    if (Math.floor(viewedDuration.value) % 30 === 0) {
      updateVideoProgress()
    }
  }
}

// 更新视频观看进度
const updateVideoProgress = async () => {
  if (!currentLesson.value || currentLesson.value.lessonType !== 'VIDEO') return
  
  try {
    await request.put(`/api/study/progress/lessons/${currentLesson.value.id}/update`, null, {
      params: {
        viewedDuration: Math.floor(viewedDuration.value)
      }
    })
  } catch (error) {
    // 忽略错误
  }
}

// 获取视频观看进度百分比
const getVideoProgress = () => {
  if (!currentLesson.value || !currentLesson.value.estimatedDuration) return 0
  const totalSeconds = currentLesson.value.estimatedDuration * 60
  return Math.min(100, Math.round((viewedDuration.value / totalSeconds) * 100))
}

// 视频播放事件
const onVideoPlay = () => {
  // 每秒更新一次进度
  videoPlayInterval.value = window.setInterval(updateVideoProgress, 1000)
}

// 视频暂停事件
const onVideoPause = () => {
  if (videoPlayInterval.value) {
    clearInterval(videoPlayInterval.value)
    videoPlayInterval.value = null
  }
}

// 视频结束事件
const onVideoEnded = () => {
  if (videoPlayInterval.value) {
    clearInterval(videoPlayInterval.value)
    videoPlayInterval.value = null
  }
  completeLesson()
}

// 获取课时相关问题
const fetchLessonQuestions = async (lessonId: number) => {
  // 如果lessonId无效，清空问题列表并返回
  if (!lessonId || lessonId <= 0) {
    lessonQuestions.value = []
    return
  }
  
  try {
    const response = await request.get(`/api/study/questions`, {
      params: {
        lessonId: lessonId,
        page: 0,
        size: 10
      }
    })
    lessonQuestions.value = response.data.content
  } catch (error) {
    ElMessage.error('获取课时问题失败')
  }
}

// 提问
const askQuestion = () => {
  if (!currentLesson.value) return
  
  router.push(`/study/questions/ask?courseId=${course.value.id}&lessonId=${currentLesson.value.id}`)
}

// 查看问题
const viewQuestion = (questionId: number) => {
  router.push(`/study/questions/${questionId}`)
}

// 刷新问题列表
const refreshQuestions = () => {
  if (currentLesson.value) {
    fetchLessonQuestions(currentLesson.value.id)
  }
}

// 查看所有课程问题
const viewAllCourseQuestions = () => {
  router.push(`/study/questions?courseId=${course.value.id}`)
}

// 工具方法
const getLessonTypeTagType = (type: string) => {
  switch (type) {
    case 'VIDEO':
      return 'primary'
    case 'DOCUMENT':
      return 'success'
    case 'TEXT':
      return 'warning'
    default:
      return 'info'
  }
}

const getLessonTypeText = (type: string) => {
  switch (type) {
    case 'VIDEO':
      return '视频'
    case 'DOCUMENT':
      return '文档'
    case 'TEXT':
      return '图文'
    default:
      return '未知'
  }
}

const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 清理定时器
const cleanup = () => {
  if (videoPlayInterval.value) {
    clearInterval(videoPlayInterval.value)
    videoPlayInterval.value = null
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLearningInfo()
})

// 组件卸载前清理
onBeforeUnmount(() => {
  cleanup()
})
</script>

<style scoped>
.learning-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.discussion-actions {
  display: flex;
  gap: 10px;
}

.course-outline-card {
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.course-outline-card .card-header h3 {
  margin: 0;
}

.modules-tree {
  flex: 1;
  overflow-y: auto;
}

.module-item {
  margin-bottom: 15px;
}

.module-header h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.lesson-item {
  padding: 8px 12px;
  margin-bottom: 5px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.lesson-item:hover {
  background-color: #f0f2f5;
}

.lesson-item.active {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
}

.lesson-item.completed {
  background-color: #f0f9ff;
}

.lesson-item.completed .lesson-title {
  color: #67c23a;
}

.lesson-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.completed-icon {
  color: #67c23a;
  font-size: 16px;
}

.lesson-type-icon {
  font-size: 16px;
}

.lesson-title {
  font-size: 14px;
  color: #606266;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.learning-content-card {
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.learning-content-card .card-header .lesson-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.lesson-content {
  flex: 1;
  overflow-y: auto;
}

.video-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.video-player {
  flex: 1;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player video {
  max-width: 100%;
  max-height: 100%;
}

.video-controls {
  margin-top: 15px;
}

.video-controls span {
  display: block;
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}

.document-content {
  height: 100%;
}

.document-viewer {
  width: 100%;
  height: 500px;
  border: none;
}

.no-document {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

.no-document .el-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.text-content {
  height: 100%;
}

.text-viewer {
  padding: 20px;
  background-color: white;
  border-radius: 4px;
  min-height: 400px;
}

.other-content {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

.no-lesson-selected {
  text-align: center;
  padding: 100px 0;
  color: #909399;
}

.no-lesson-selected .el-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.discussion-card {
  margin-bottom: 20px;
  height: calc(60vh - 20px);
  display: flex;
  flex-direction: column;
}

.questions-list {
  flex: 1;
  overflow-y: auto;
}

.question-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f2f5;
  cursor: pointer;
}

.question-item:last-child {
  border-bottom: none;
}

.question-item:hover {
  background-color: #f5f7fa;
}

.question-title {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.question-meta {
  display: flex;
  gap: 10px;
  font-size: 12px;
  color: #909399;
}

.no-questions {
  text-align: center;
  color: #909399;
  margin: 20px 0;
}

.progress-stats-card {
  height: calc(40vh - 20px);
}

.stats-info {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.stat-item {
  flex: 1;
}

.stat-label {
  margin: 0 0 5px 0;
  color: #606266;
  font-size: 14px;
}

.stat-value {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}
</style>